#include <Engine/StdAfx.h>
#include <Engine/Misc/Profiler.h>
#include <Engine/GlobalEnv.h>
#include <Engine/ITimer.h>
#include <Engine/IEngine.h>

using namespace fastbird;

namespace fastbird
{
	int Profiler::indent = 0;
	Profiler::MSG_STACK Profiler::msgs;
}
Profiler::Profiler(const char* name)
	: mName(name)
{
	mStartTick = gEnv->pTimer->GetTickCount();
	indent++;
}

Profiler::~Profiler()
{
	indent--;
	ITimer::TIME_PRECISION elapsedTime = (gEnv->pTimer->GetTickCount() - mStartTick) / (ITimer::TIME_PRECISION)gEnv->pTimer->GetFreq();
	char sp[10];
	memset(sp, '\t', 10);
	if (indent>9)
		sp[9] = 0;
	else
		sp[indent] = 0;
	if (indent!=0)
	{
		char buffer[255];
		sprintf_s(buffer, 255, "%s[Profiler] %s takes %f secs.", sp, mName.c_str(), elapsedTime);
		msgs.push(buffer);
	}
	else
	{
		IEngine::Log("%s[Profiler] %s takes %f secs.", sp, mName.c_str(), elapsedTime);
		// print stack
		while(!msgs.empty())
		{
			IEngine::Log(msgs.top().c_str());
			msgs.pop();
		}
		
	}
}